package com.example.finalssm.Controller;

import com.example.finalssm.mapper.UserMapper;
import com.example.finalssm.pojo.User;
import com.example.finalssm.utils.MybatisUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/blogger")
public class LoginController {
    @RequestMapping("/login")
    public String identifyLogin(@RequestParam(value = "username") String username,
                                @RequestParam(value = "password") String password,
                                Model model, HttpSession session
    ) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("password", password);
        User userMap = MybatisUtils.getSqlSession().getMapper(UserMapper.class).getUser(map);
        //通过userMap来判断
        if (userMap == null) {
            model.addAttribute("error", "登录失败，账号或者密码错误");
            return "redirect:index.html";
        }
        else{
            session.setAttribute("username",username);
            session.setAttribute("password",password);
            //登陆成功，把每个用户的主键存到session，方便后续的表crud
            session.setAttribute("userId",userMap.getUserId());
            return "redirect:Main.html";
        }
    }
}
